package com.eascs.p2p.admin.manager.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.eascs.common.util.StringUtil;
import com.eascs.p2p.admin.manager.IFileManager;
import com.eascs.p2p.common.dao.BaseDao;
import com.eascs.p2p.common.entity.FileEntity;

@Repository
public class FileManagerImpl extends BaseDao implements IFileManager{
	
	
	@Override
	public List<FileEntity> findFileByKeyCode(String[] type, String id){
		
		StringBuffer sql=new StringBuffer();
		List<Object> listParams = new ArrayList<Object>();
		sql.append("select * from p2p_file p where 1=1");
		if(id!=null){
			sql.append(" and p.key_code = ? ");
			listParams.add(id);
		}
		if(type!=null){
			if(type.length==1){
				sql.append(" and p.file_type_code = ? ");
				listParams.add(type[0]);
			}
			if(type.length==2){
				sql.append(" and ( p.file_type_code = ? ");
				listParams.add(type[0]);
				sql.append(" or p.file_type_code = ? ) ");
				listParams.add(type[1]);
			}
			if(type.length>2){
				sql.append(" and ( p.file_type_code = ? ");
				listParams.add(type[0]);
				for (int i = 1; i < type.length-1; i++) {
					sql.append(" or p.file_type_code = ? ");
					listParams.add(type[i]);
				}
				sql.append(" or p.file_type_code = ? ) ");
				listParams.add(type[type.length-1]);
			}
		}
		List<FileEntity> list=this.findEntitys(sql.toString(), FileEntity.class,listParams.toArray());
		return list;
		
	}

	@Override
	public FileEntity findFileById(String id) {
		
		StringBuffer sql=new StringBuffer();
		sql.append("select * from p2p_file p where 1=1");
		sql.append(" and p.file_id = ? ");
		FileEntity fileEntity=this.findEntity(sql.toString(), FileEntity.class,id);
		return fileEntity;
		
	}

	@Override
	public Boolean save(FileEntity fileEntity) {
		return this.insert(fileEntity);
	}
	
	
	@Override
	public Boolean delFile(String fileId) {
		return this.execute("delete from p2p_file where file_id = ?", fileId);
	}
	
	@Override
	public Boolean updateFile(String[] fileId, String keyCode){
		boolean flag=true;
		if(fileId!=null&&fileId.length>0){
			for (int i = 0; i < fileId.length; i++) {
				if(StringUtil.isNotBlank(fileId[i])){
					flag =this.execute("update  p2p_file set key_code = ? where file_id = ? ",keyCode, fileId[i]);
				}
				if(flag==false){
					break;
				}
			}
		}
		return flag;
	}
}
